package com.hevs.samplewebapp.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.hevs.samplewebapp.server.entities.User;
import com.hevs.samplewebapp.server.json.ObjectMapperFactory;
import com.hevs.samplewebapp.server.service.UserService;

public class UserServlet extends SessionAuthHttpServlet {

	public UserServlet() {
		super(3);
	}

	/**
	 * @author Arnaud Durand
	 */
	private static final long serialVersionUID = 8161966306277949201L;

	
	public static UserService userService;
	{
		userService = new UserService();
	};

	@Override
	protected void doSecurePut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		

			// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
			// globall
			BufferedReader reader = req.getReader();
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			reader.close();
			System.out.println(sb.toString());

			ObjectMapper mapper = ObjectMapperFactory.get();
			User user = mapper.readValue(sb.toString(), User.class);

			// throw bad request
			if (user == null) {
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
				return;
			}
			userService.updateUser(user);
	}

	@Override
	protected void doSecureDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
			// ObjectMapper mapper = new ObjectMapper(); // can reuse, share
			// globall
			BufferedReader reader = req.getReader();
			StringBuilder sb = new StringBuilder();
			String line = reader.readLine();
			while (line != null) {
				sb.append(line + "\n");
				line = reader.readLine();
			}
			reader.close();
			System.out.println(sb.toString());

			ObjectMapper mapper = ObjectMapperFactory.get();
			User user = mapper.readValue(sb.toString(), User.class);

			// throw Error 400
			if (user == null || user.getKey() == null) {
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
				return;
			}

			userService.removeUser(user);

	}

	@Override
	protected void doSecureGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

			List<User> users = userService.getAllUsers();

			ObjectMapper mapper = ObjectMapperFactory.get();
			resp.setContentType("application/json");
			PrintWriter writer = resp.getWriter();
			writer.write(mapper.writeValueAsString(users));
			writer.flush();
	}

}
